//
//  ComposeViewController.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/16.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit
import SVProgressHUD

// MARK: - 编写微博 控制器
class ComposeViewController: UIViewController {

    /// 图片选择控制器
    private var picController: PicturePickerController = PicturePickerController()
    
    // MARK: - 监听事件
    /// 关闭当前控制器
    @objc private func closeController() {
        
        composeView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //发送微博
    @objc private func sendStatus() {
        
        let text = composeView.emoticonText
        let image = picController.pictures.last
        /// 发送图文微博
        NetworkTools.sharedTools.sendStatus(text, image: image) { (success, failure) -> () in
            
            if failure != nil {
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
        }
        //关闭控制器
        closeController()
    }
    
    /// 键盘事件响应
    @objc private func keyboardChanged(notification: NSNotification) {
        //键盘大小
        let rect = (notification.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        let curve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offset = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        //更新布局
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    /// 点击表情按钮
    @objc private func clickEmoticonButton() {
        //取消
        composeView.resignFirstResponder()
        //更换
        composeView.inputView = composeView.inputView == nil ? emoticonView : nil
        //重设
        composeView.becomeFirstResponder()
    }
    
    /// 点击选择图片按钮
    @objc private func selectPicture() {
//        print("选择照片 \(picController.view.frame.height)")
        composeView.resignFirstResponder()
        
        if picController.view.frame.size.height > 0 {
            return
        }
        
        picController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        composeView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view)
            make.bottom.equalTo(picController.view.snp_top)
            make.right.equalTo(view)
        }
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
//        print(picController.view.frame.height)
    }
    
    // MARK: - 视图生命周期
    override func loadView() {
        
        view = UIView()
        
        automaticallyAdjustsScrollViewInsets = false
        
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let center = NSNotificationCenter.defaultCenter()
        
        center.addObserver(self,
                selector: "keyboardChanged:",
                name: UIKeyboardWillChangeFrameNotification,
                object: nil)
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // TODO: 667 / 0
        print(picController.view.frame)
        if picController.view.bounds.height == 667 {
            composeView.becomeFirstResponder()
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 懒加载控件 
    /// 工具条
    private lazy var toolbar: UIToolbar = UIToolbar()
    /// 文本视图
    private lazy var composeView: UITextView = {
        let textView = UITextView()
        
        textView.textColor = UIColor.darkGrayColor()
        textView.font = UIFont.systemFontOfSize(18)
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置代理
        textView.delegate = self
        return textView
    }()
    /// 占位标签
    private lazy var placeholderLabel: UILabel = UILabel(title: "新鲜事",
        color:  UIColor.lightGrayColor(),
        textSize: 18)
    private lazy var emoticonView: EmoticonView = EmoticonView { [weak self](emoticon) -> () in
        self?.composeView.insertEmoticon(emoticon)
    }
}

// MARK: - TextView代理方法
extension ComposeViewController: UITextViewDelegate {
    
    //输入文本时 隐藏占位标签 显示'发布'按钮
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeholderLabel.hidden = textView.hasText()

    }
}

// MARK: - 设置界面 UI
private extension ComposeViewController {
    
    /// 设置 UI
    func setupUI() {
        view.backgroundColor = UIColor.whiteColor()

        prepareForNavigationBar()
        prepareForToolbar()
        prepareForTextView()
        prepareForPicturePickerController()
    }
    
    func prepareForPicturePickerController() {
        addChildViewController(picController)
        
        view.insertSubview(picController.view, belowSubview: toolbar)
        
        picController.view.snp_makeConstraints { (make) -> Void in
            make.height.equalTo(0)
            make.left.equalTo(view)
            make.bottom.equalTo(view)
            make.right.equalTo(view)
            
        }
    }
    
    /// 准备文本输入框
    func prepareForTextView() {
        
        view.addSubview(composeView)
        
        composeView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view)
            make.bottom.equalTo(toolbar.snp_top)
            make.right.equalTo(view)
        }
        
        composeView.addSubview(placeholderLabel)
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(composeView).offset(8)
            make.left.equalTo(composeView).offset(5)
        }
    }
    
    /// 准备工具条
    func prepareForToolbar() {
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        //添加控件
        view.addSubview(toolbar)
        //自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.height.equalTo(44)
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(view)
        }
        
        // 3. 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture",
                                "actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background",
                                "actionName": "clickEmoticonButton"],
                            ["imageName": "compose_addbutton_background"]]
        

        //item 数组
        var toolbarItems = [UIBarButtonItem]()
        
        //遍历 字典数组
        for buttonName in itemSettings {
            let item = UIBarButtonItem(imageName: buttonName["imageName"]!,
                            target: self,
                            actionName: buttonName["actionName"])
            
            toolbarItems.append(item)
            
            //添加弹簧
            toolbarItems.append(UIBarButtonItem(barButtonSystemItem:.FlexibleSpace,
                target: nil,
                action: nil))
        }
        
        toolbarItems.removeLast()
        
        toolbar.items = toolbarItems
    }
    
    /// 准备导航条
    func prepareForNavigationBar() {
        
        // 设置左右 Item 添加点击事件的监听
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消",
            style: UIBarButtonItemStyle.Plain,
            target: self,
            action: "closeController")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布",
            style: UIBarButtonItemStyle.Plain,
            target: self,
            action:  "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        //自定义 titleview
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        navigationItem.titleView = titleView
        
        let titleLabel: UILabel = UILabel(title: "发微博",textSize: 15)
        
        let namelabelText = UserAccountViewModel.sharedUserAccount.account?.screenName
        let nameLabel: UILabel = UILabel(title:namelabelText ?? "",
            color: UIColor.lightGrayColor(),
            textSize: 13)
        
        //添加titleView子控件
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        //自动布局
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView)
        }
    }
}






